package com.example.lenovo0509;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;

import com.example.lenovo0509.bean.NewsBean;
import com.example.lenovo0509.bean.NewsInfoBean;
import com.example.lenovo0509.utils.HttpUtils;
import com.example.lenovo0509.utils.URLUtils;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    ListView newsLv;
    String type="top";
    String newsUrl;
    private static final String TAG = "MainActivity";

    private NewsListAdapter adapter;
    List<NewsBean>newsList;
    List<String>deleteNews;//存储删除的新闻信息
    @SuppressLint("HandlerLeak")
    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==1) {
                String json= (String) msg.obj;
                NewsInfoBean infoBean = new Gson().fromJson(json, NewsInfoBean.class);
                List<NewsInfoBean.ResultBean.DataBean> data = infoBean.getResult().getData();
                adapter=new NewsListAdapter(MainActivity.this,data,deleteNews);
                newsLv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        newsLv=findViewById(R.id.news_lv);

        try {
            String encode = URLEncoder.encode(type, "UTF-8");
            newsUrl=URLUtils.getNewsUrl(encode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

         loadData(newsUrl);//开始网络请求


    }

    private void loadData(final String newsUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = HttpUtils.getJsonByNetwork(newsUrl);
                Log.d(TAG, "newsUrl: "+newsUrl);
                Log.d(TAG, "json: "+json);
                Message msg=handler.obtainMessage();
                msg.what=1;
                msg.obj=json;
                handler.sendMessage(msg);
            }
        }).start();
    }
}
